Observable unsubscribe

Descripcion

Como manejar un array de observable para dessubscribirse cuando se destruye el componente.

Unsubscribe onDestroy

Los pasos son los siguientes:

A continuación un ejemplo:

export class OptionsButtonsComponent implements OnInit {
  highlightHistory:boolean = false;
  highlightTemplates:boolean = false;

  private subscriptions: Subscription[] = [];

  constructor(
    private optionsMenuService: OptionsMenuService,
    private optionsButtonsService: OptionsButtonsService
    ) {}

  ngOnInit(): void {
    this.setSubscriptions();
  }

  setSubscriptions() {
    this.subscriptions = [
      this.optionsButtonsService.templatesHighlight$.subscribe(() =>
        this.setHighlightTemplates(),
      ),
      this.optionsButtonsService.historyHighlight$.subscribe(() =>
        this.setHighlightHistory(),
      ),
      this.optionsButtonsService.noneHighlight$.subscribe(() =>
        this.setHighlightNone(),
      )
    ];
  }

  toggleTemplates() {
    this.optionsMenuService.toggleTemplatesSideNav();
  }

  toggleHistory() {
    this.optionsMenuService.toggleHistorySideNav();
  }

  setHighlightHistory(){
    this.highlightHistory = true
    this.highlightTemplates = false
  }

  setHighlightTemplates(){
    this.highlightTemplates = true
    this.highlightHistory = false
  }

  setHighlightNone(){
    this.highlightTemplates = false
    this.highlightHistory = false
  }

  ngOnDestroy() {
    for (const subscription of this.subscriptions) {
      subscription.unsubscribe();
    }
  }
}
Alternativa con DestroyRef

Podemos usar el servicio DestroyRef para programa el unsubscribe directamente en el momento en el que nos subscribimos:

En el construcitr inyectamos el servicio DestroyRef:

  constructor(
    private destroyRef: DestroyRef,
  ) { }

Cuando nos subscribimos a un observable usamos un pipe de la siguiente manera:

.pipe(takeUntilDestroyed(this.destroyRef))

Un ejemplo completo del subscribe es el siguiente (en este caso es un observable sobre los cambios de un formGroup):

this.categoryFormGroup
        .get(family.id).valueChanges
        .pipe(takeUntilDestroyed(this.destroyRef))
        .subscribe((checkboxState) => {
          this.categoryPanel.setCategoriesFromFamilies(family.id, checkboxState);
          this.validateStep();
        });
Tags

Angular | Observable | subscription